<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebGL 演示多次绘制</title>
    <script src="./common.js">  </script>
</head>

<body>
    <div>
        <p>研究WebGL多次绘制的方法</p>
        <p>研究多次绘制的最少执行代码</p>
    </div>
    <canvas id="webgl" width="500" height="500" style="background-color: #0d72da"></canvas>
    <div>
        <button onclick="changeBuffer()">修改顶点缓冲区</button>
        <button onclick="reset()">复原</button>
        <button onclick="loop()">循环</button>
    </div>
    <script type="module">
        const canvas = document.getElementById('webgl');
        const gl = canvas.getContext('webgl');

        import { vertex, fragment } from "./shader.js"

        //初始化着色器
        const program = initShader(gl, vertex, fragment);

        //获取顶点着色器的位置变量apos
        const aposLocation = gl.getAttribLocation(program, 'apos');

        //创建缓冲区对象
        const buffer = gl.createBuffer();
        //绑定缓冲区对象
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        //9个元素构建三个顶点的xyz坐标值
        const vertexArray = new Float32Array([
            0.0, 0.0, 0.0,//顶点1坐标
            1.0, 0.0, 0.0,//顶点2坐标
            0.0, 1.0, 0.0,//顶点3坐标
        ]);

        //第二个代码案例vertexAttribPointer方法的第二个参数是2，这里是3
        gl.vertexAttribPointer(aposLocation, 3, gl.FLOAT, false, 0, 0);
        //允许数据传递
        gl.enableVertexAttribArray(aposLocation);

        renderTriangle(vertexArray);


        function renderTriangle(vertexArray, clearValue) {
            clearValue = clearValue || { r: 0.5, g: 0.5, b: 0.5, a: 1.0 };
            gl.clearColor(clearValue.r, clearValue.g, clearValue.b, clearValue.a);
            gl.clear(gl.COLOR_BUFFER_BIT);

            //顶点数组data数据传入缓冲区
            gl.bufferData(gl.ARRAY_BUFFER, vertexArray, gl.STATIC_DRAW);
            //开始绘制图形，使用TRIANGLES模式，三点构成一个平面
            gl.drawArrays(gl.TRIANGLES, 0, 3);
        }

        
        import ChangeBuffer from "../Common/ChangeBuffer.js";
        let cb = new ChangeBuffer(renderTriangle);
        reset();
        
    </script>
</body>

</html>